package org.smile.orm.xml.execut;

import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import org.smile.db.SqlRunException;
import org.smile.db.Transaction;
import org.smile.db.sql.BoundSql;
import org.smile.db.sql.SQLRunner;
import org.smile.orm.OrmApplication;
import org.smile.orm.ann.ArrayBound;
import org.smile.orm.executor.MappedOperator;
import org.smile.orm.mapping.BoundOrmTableMapping;
import org.smile.orm.mapping.OrmTableMapping;
import org.smile.orm.result.ResultType;
import org.smile.template.StringTemplate;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {})
@XmlRootElement(name = "update")
public class UpdateOperator extends Operator{

	@Override
	public SQLRunner createSQLRunner(Transaction conn,MappedOperator operator,Object param) {
		return new SQLRunner(conn);
	}
	
	@Override
	protected void initAnnotationSql(OrmApplication application, OrmTableMapping mapping, Method method) {
		sql=mapping.getUpdateByIdSql();
	}

	@Override
	public StringTemplate initSimpleSqlTemplateFromExeParam(String scriptType, BoundOrmTableMapping tableMapper) {
		return new StringTemplate(scriptType, tableMapper.getUpdateByIdSql());
	}

	@Override
	public Object executeBoolean(SQLRunner runner,  BoundSql boundSql) {
		boolean multi=boundSql.checkMultiSql();
		if(multi){//多语句执行
			if(boundSql instanceof ArrayBound){
				throw new SqlRunException("array parameter not support multi sql");
			}
			List<String> multiSql=boundSql.getMultiSql();
			Object res=null;
			for(String sql:multiSql){
				boundSql.setSql(sql);
				res=runner.execute(boundSql);
			}
			return res;
		}else{
			return runner.execute(boundSql);
		}
	}
}
